const { APP_HOST, APP_PORT } = require('../app/config')
const uploadService = require('../service/upload.service')

const { UPLOAD_PATH } = require("../config/path")
const fs = require('fs')

class FileController {
  async created(ctx) {
    // 1.获取上传文件的数据
    console.log(ctx.request.file)
    const { filename, mimetype, size } = ctx.request.file
    const { category, remark } = ctx.request.body
    console.log(category, remark)
    const { id } = ctx.request.params
    console.log(id)

    const avatarUrl = `${APP_HOST}:${APP_PORT}/upload/photo/${id}`

    // 2.操作数据库
    await uploadService.created(avatarUrl, filename, mimetype, size, category, remark)


    // 把头像的信息，保存在url表中
    // const result2 = await userService.updateUserAvatar(avatarUrl, id)
    // console.log(result)
    ctx.body = {
      code: 0,
      message: '头像上传成功~~',
      data: {
        avatarUrl: avatarUrl
      }
    }
  }
  // 根据id查看照片
  async showImageById(ctx) {
    // 1拿到上传头像的用户ID
    const { id } = ctx.request.params
    // console.log(id)
    // 2.根据id查找照片信息
    const avatarInfo = await uploadService.findPhotoById(id)
    // console.log('avatarInfo=>', avatarInfo)
    // 3.读取照片所在文件
    const { filename, mimetype } = avatarInfo
    // console.log(filename, mimetype)

    ctx.type = mimetype

    let avatar_url = fs.createReadStream(`${UPLOAD_PATH}/${filename}`)
    // console.log(avatar_url)
    ctx.body = avatar_url

    // ctx.body = {
    //     code: 0,
    //     message: '查找头像成功~',
    //     data: avatarInfo
    // }
  }

}
module.exports = new FileController() 